package com.example.cheng.dao;

import com.example.cheng.entity.Student;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StuDao {
    //test
    public static void main(String[] args){
        try {
            getAllStu(null);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    //检查登录是否正确
    public static boolean checkStu(Student student) throws SQLException {
        Connection connection=BaseDao.getConn();
        String sql="select * from tbl_student where stuno=? and stuname=? and role=?";//占位符，？有编号，从1开始编起
        PreparedStatement pst=connection.prepareStatement(sql);//创建执行sql命令对象
        pst.setString(1,student.getNo());
        pst.setString(2,student.getName());
        pst.setInt(3,student.getRole());
        ResultSet resultSet=pst.executeQuery();
        if (resultSet.next()){
            return true;
        }
        pst.close();
        resultSet.close();
        connection.close();
        return false;
    }

    //查询表中所有的数据
    public static List getAllStu(String stuno) throws SQLException {
        List list=new ArrayList();
        Connection connection=BaseDao.getConn();//获取连接对象
        String sql=null;
        if (stuno==null){
            sql="select * from tbl_student";//管理员的查询，查询全部
        }else {
            sql="select * from tbl_student where stuno="+stuno;//普通用户的查询，查询自身
        }
        PreparedStatement pst=connection.prepareStatement(sql);
        ResultSet resultSet=pst.executeQuery();//记录集
        while (resultSet.next()){
            //读取每一行数据
            String no=resultSet.getString("stuno");
            String name=resultSet.getString("stuname");
            String tel=resultSet.getString("tel");
            String role=resultSet.getString("role");
//            System.out.println(no+","+name+","+tel);
            Student student=new Student(no,name,tel,Integer.parseInt(role));
            list.add(student);
        }
        pst.close();
        resultSet.close();
        connection.close();
        return list;
    }

}
